﻿using Common;
using DBUtility;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseDal
{
    /// <summary>
    /// AssetKeepWarnDal 类实现了资产维护提醒的数据访问层。
    /// 该类采用单例模式，确保只有一个实例存在。
    /// </summary>
    public class AssetKeepWarnDal
    {
        // 使用 Lazy<T> 实现单例模式，确保实例的惰性初始化和线程安全。
        private static readonly Lazy<AssetKeepWarnDal> _instance = new Lazy<AssetKeepWarnDal>(() => new AssetKeepWarnDal());

        /// <summary>
        /// 获取类的单例实例。
        /// </summary>
        public static AssetKeepWarnDal Instance { get; } = _instance.Value;

        // 私有构造函数，防止外部实例化该类。
        private AssetKeepWarnDal() { }

        private const string tableName = "AssetKeepWarn";

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from " + tableName);
            strSql.Append(" where IsDelete=0 " + strWhere);
            return SqlHelper.Exists(strSql.ToString());
        }

        /// <summary>
        /// 查询SQL语句
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public StringBuilder GetSelectSql(string strWhere = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT ID,AssetNo,AssetName,Specs,MaintainTimeStart,MaintainTimeEnd,Person,Status,");
            sb.Append("Remark,CreateTime,AU_ID ");
            sb.Append("FROM " + tableName);
            sb.Append(" Where IsDelete=0 ");

            if (!string.IsNullOrEmpty(strWhere))
            {
                sb.Append(strWhere);
            }

            return sb;
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder sb = GetSelectSql(strWhere);
            string countSql = PageHelper.CreateCountingSql(sb.ToString());
            recordCount = Convert.ToInt32(SqlHelper.GetSingle(countSql));
            string pageSql = PageHelper.CreatePageSql(recordCount, pageSize, pageIndex, sb.ToString(), filedOrder);
            DataSet ds = SqlHelper.Query(pageSql);
            return ds.Tables[0];
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public List<AssetKeepWarn> GetList(string strWhere)
        {
            StringBuilder sb = GetSelectSql(strWhere);
            DataSet ds = SqlHelper.Query(sb.ToString());
            return CommonOperation.ConvertDataTableToModelList<AssetKeepWarn>(ds.Tables[0]);
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AssetKeepWarn GetModelById(decimal id)
        {
            var sb = GetSelectSql("and ID=@id");

            SqlParameter[] parameters =
            {
                new SqlParameter("@id",id)
            };
            DataSet ds = SqlHelper.Query(sb.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                var model = CommonOperation.DataTableToModel<AssetKeepWarn>(ds.Tables[0]);
                return model;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 派单或转单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DispatchOrRelay(AssetKeepWarn model)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"Update {tableName} SET ");
            sb.Append("Person=@person,");
            sb.Append("Remark=@remark,");
            sb.Append("Status=3 ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                new SqlParameter("@person",model.Person),
                new SqlParameter("@remark",model.Remark),
                new SqlParameter("@id",model.ID)
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int UpdateStatus(decimal id, int status, string userName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"Update {tableName} SET ");
            sb.Append("Status=@status,");
            sb.Append("Auditor=@auditor,");
            sb.Append("AuditTime=GetDate() ");
            sb.Append("WHERE ID=@id");
            SqlParameter[] parameters = {
                new SqlParameter("@status",status),
                new SqlParameter("@auditor",userName),
                new SqlParameter("@id",id)
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 撤销维护登记后将维护提醒的状态修改回 3：待处理
        /// </summary>
        /// <param name="auid">维护登记ID</param>
        /// <returns></returns>
        public int AfterDelete(decimal auid, string assetNo)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"Update {tableName} SET ");
            sb.Append("Status=3 ");
            sb.Append("WHERE AU_ID=@auid and AssetNo=@assetNo");
            SqlParameter[] parameters = {
                new SqlParameter("@auid",auid),
                new SqlParameter("@assetNo",assetNo)
            };
            int result = SqlHelper.ExecuteSql(sb.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 定时任务批量新增
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int AddList(List<AssetKeepWarn> list)
        {
            List<CommandInfo> sqllist = new List<CommandInfo>();
            CommandInfo cmd;

            StringBuilder sb_D;
            foreach (AssetKeepWarn d in list)
            {
                sb_D = new StringBuilder();
                sb_D.Append("insert into " + tableName + "(");
                sb_D.Append("AssetNo,AssetName,Specs,MaintainTimeStart,MaintainTimeEnd,Status,CreateTime)");
                sb_D.Append(" values (");
                sb_D.Append("@assetNo,@assetName,@specs,@maintainTimeStart,@maintainTimeEnd,2,GETDATE())");
                SqlParameter[] parameters2 = {
                            new SqlParameter("@assetNo",  d.AssetNo),
                            new SqlParameter("@assetName", d.AssetName),
                            new SqlParameter("@specs",  d.Specs),
                            new SqlParameter("@maintainTimeStart", d.MaintainTimeStart),
                            new SqlParameter("@maintainTimeEnd", d.MaintainTimeEnd)
                    };
                cmd = new CommandInfo(sb_D.ToString(), parameters2);
                sqllist.Add(cmd);
            }

            int count = SqlHelper.ExecuteSqlTran(sqllist);

            return count;
        }

    }
}
